auto.waitFor()
setScreenMetrics(1080, 1920);

var isshowadvice = false
var isshowhongbao = false
var repeat_num = 5

//主线程
log(threads.currentThread())

//线程1 每隔1s监听是否产生广告
var adtask = threads.start(function(){
    setInterval(function(){
        if(isshowadvice){
            log("检测到有广告，自动处理广告")
            //TODO something

            //isshowadvice = false
            update_ad_flag()
        }else{
            log("没有广告，继续运行")
        }
    }, 1000)
})
adtask.waitFor()

//线程2 每隔1s监听是否产生红包
var hongbaotask = threads.start(function(){
    setInterval(function(){
        if(isshowhongbao){
            log("检测到有红包，自动处理红包")
            //TODO something

            //isshowhongbao = false
            update_hongbao_flag()
        }else{
            log("没有红包，继续运行")
        }
    }, 1000)
})
hongbaotask.waitFor()

//主线程，仅为了模拟产生红包和广告
var runnum = 0
var cre_ad_cronid = setInterval(create_ad_or_hongbao, 5000)

function create_ad_or_hongbao(){
    var rnum = random(1,2)
    if(rnum==1){
        log("产生广告")
        //isshowadvice = true
        update_ad_flag()
    }else{
        log("产生红包")
        //isshowhongbao = true
        update_hongbao_flag()
    }
    
    runnum++
    if(runnum>=repeat_num){
        log("达到最大次数，停止运行")
        clearTimeout(cre_ad_cronid)
        threads.shutDownAll()
    }
}

//线程安全-更新ad标记
function update_ad_flag(){
    sync(function(){
        isshowadvice = !isshowadvice
        log("isshowadvice:"+isshowadvice)
    })()
}

//线程安全-更新hongbao标记
function update_hongbao_flag(){
    sync(function(){
        isshowhongbao = !isshowhongbao
        log("isshowhongbao:"+isshowhongbao)
    })()
}